<template>

  <div class="app-container">
    <el-row :gutter="20" class="row-con">
      <!--侧边工厂树数据-->
      <el-col :xs="9" :sm="6" :md="7" :lg="5" :xl="6">
        <el-card class="box-card card">
          <div class="head-container">
            <el-input
              v-model="filterText"
              clearable
              size="small"
              placeholder="输入名称搜索"
              prefix-icon="el-icon-search"
              class="filter-item"
            />
          </div>

          <el-tree
            class="filter-tree"
            ref="factoryTree"
            :load="loadNode"
            :props="defaultProps"
            :filter-node-method="filterNode"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            lazy
            v-loading="treeLoading"
            node-key="id"
          >
          </el-tree>
        </el-card>
      </el-col>

      <el-col :xs="10" :sm="13" :md="12" :lg="14" :xl="13">
        <el-card class="box-card">
          <el-calendar v-model="value">
            <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
            <template
              slot="dateCell"
              slot-scope="{date, data}">
              <div style="height:100%;padding:8px;" @click="technology(data.day)">
                <p :class="data.isSelected ? 'is-selected' : ''">
                  {{ data.day.split('-').slice(2).join('-') }} <br>
                  {{breakDate.indexOf(data.day) == -1 ? "工作日":"休息日"}}
                  {{ data.isSelected ? '✔️' : ''}}
                </p>
              </div>
            </template>
          </el-calendar>
        </el-card>
      </el-col>

      <el-col :xs="5" :sm="5" :md="5" :lg="5" :xl="5">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>班次信息</span>
          </div>
          <div v-if="flightInformation.length > 0" v-for="item in flightInformation" :key="item.id" class="text item">
            <h3 style="margin-top: 20px">班次信息</h3>
            {{'班次名称 : ' + item .shiftName}}<br>
            {{'班次时间 : ' + item .startTime + "~~"+ item .endTime}}<br>
            {{'是否跨天 : ' +(item.isAcross == 0 ? "否" : "是")}}<br>
            {{'班组负责人 : '+(item.principal == undefined?'':item.principal)}}<br>
            {{'班组人数 : ' +item.factoryTeamEmployees.length}}

            <h4 style="margin-top: 20px">班次停机信息</h4>
            <div v-for="t in item.factoryShiftTimes" :key="t.id">
              <div>
                <span v-if="( t.type === item.value)" v-for="item in dict.classes_type" :key="item.id">
                  {{('停机类型 : ' + item.label)}}
                </span><br>
                {{'停机时间 : ' + t .startTime + "~~"+ t .endTime}}<br>
                {{'是否跨天 : ' +(t.isAcross == 0 ? "否" : "是")}}<br>
              </div>
            </div>
          </div>
          <div v-if="flightInformation.length == 0" class="text item">
            暂无数据
          </div>
        </el-card>

        <!-- <el-card class="box-card">
           <div slot="header" class="clearfix">
             <span>班计划停机信息</span>
           </div>
           <div v-for="o in 4" :key="o" class="text item">
             {{'列表内容 ' + o }}
           </div>
         </el-card>-->
      </el-col>
    </el-row>
  </div>

</template>

<script>
  import crudFactoryModel from "@/api/factory/factoryModel";
  import CRUD, {presenter, header, form, crud} from "@crud/crud";
  import rrOperation from "@crud/RR.operation";
  import crudOperation from "@crud/CRUD.operation";
  import udOperation from "@crud/UD.operation";
  import pagination from "@crud/Pagination";
  import classes from "./index";
  import planHaltProduction from "../plan_halt_production/index";

  const defaultForm = {
    id: null,
    modelCode: null,
    modelName: null,
    modelType: null,
    remark: null,
    pid: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
  };
  export default {
    name: "ShiftDetails",
    components: {
      pagination,
      crudOperation,
      rrOperation,
      udOperation,
      classes,
      planHaltProduction
    },
    mixins: [presenter(), header(), form(defaultForm), crud()],
    dicts: ['classes_type'],
    cruds() {
      return CRUD({
        title: "建模",
        url: "api/factoryModel",
        idField: "id",
        sort: "id,desc",
        queryOnPresenterCreated: false,
        crudMethod: {...crudFactoryModel},
      });
    },
    watch: {
      //搜索框
      filterText(val) {
        this.$refs.factoryTree.filter(val);
      },
      value: {//监听月份变化
        handler(val) {
          // console.log(this.dateFormat(val, "yyyy-MM-dd"));
          this.vacation({"years": this.dateFormat(val, "yyyy-MM"), templateCode: this.modelCode})
        }
      }
    },
    computed: {
      currentName() {
        return this.types[this.detailsData.modelType];
      },
      chidrenName() {
        return this.types[this.detailsData.modelType * 1 + 1];
      },
    },
    data() {
      return {
        pid: null,
        //权限
        permission: {
          add: ["admin", "factoryModel:add"],
          edit: ["admin", "factoryModel:edit"],
          del: ["admin", "factoryModel:del"],
        },
        //搜索框数据
        filterText: "",
        treeLoading: false,
        treeNode: null,
        modelCode: "",
        activeName: 'first',
        value: "",
        breakDate: [],
        flightInformation: [],
        //树配置
        defaultProps: {
          children: "children",
          label: "modelName",
        },
        //详情数据
        detailsData: defaultForm,
        types: {
          0: "工厂",
          1: "车间",
          2: "产线",
          3: "工段",
          4: "工位",
        },
      };
    },
    methods: {
      //过滤
      filterNode(value, data) {
        if (!value) return true;
        return data.modelName.indexOf(value) !== -1;
      },
      //Tabs 切换
      handleClick(tab, event) {
        if (tab.name == "first") {
          this.$refs.first.queryPage(this.modelCode);
        } else if (tab.name == "second") {
          this.$refs.second.queryPage(this.modelCode);
        }
      },
      //加载树
      loadNode(node, resolve) {
        this.treeLoading = true;
        const params = {pid: 0, id: null};
        if (node.level === 0) {
          params.pid = 0;
          // 树的根节点的传参，需带上父组件传来的ID，否则一个页面会有多个根节点
        } else {
          params.pid = node.data.id;
        }
        let arr = ["0", "1", "2"]
        setTimeout(() => {
          crudFactoryModel.getModels(params).then((res) => {
            let list = []
            //过滤数组只展示0：工厂，1：车间，2：产线
            res.content.forEach((item) => {
              if (arr.some(ele => ele == item.modelType)) {
                list.push(item)
              }
            })
            if (!this.modelCode) {
              this.modelCode = list[0].modelCode
              this.vacation({templateCode: this.modelCode})
              this.getFlightInformation({templateCode: this.modelCode})
            }
            resolve(list);
            this.treeData = res.content;
            this.treeLoading = false;
          });
        }, 200);
      },
      //树点击事件
      handleNodeClick(data, node) {
        this.modelCode = node.data.modelCode;
        // console.log(this.value);
        if (this.value) {
          this.vacation({"years": this.dateFormat(this.value, "yyyy-MM"), templateCode: this.modelCode})
        } else {
          this.vacation({templateCode: this.modelCode})
        }
        //获取班次信息
        this.getFlightInformation({templateCode: this.modelCode})
      },
      technology(data) {
        this.getFlightInformation({currentTime:data,templateCode: this.modelCode})
        console.log(data);
      },
      dateFormat(date, fmt) {
        date = new Date(date)
        var a = ['日', '一', '二', '三', '四', '五', '六']
        var o = {
          'M+': date.getMonth() + 1, // 月份
          'd+': date.getDate(), // 日
          'h+': date.getHours(), // 小时
          'm+': date.getMinutes(), // 分
          's+': date.getSeconds(), // 秒
          'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
          'S': date.getMilliseconds(), // 毫秒
          'w': date.getDay(), // 周
          'W': a[date.getDay()], // 大写周
          'T': 'T'
        }
        if (/(y+)/.test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
        }
        for (var k in o) {
          if (new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
          }
        }
        return fmt
      },
      vacation(data) {
        crudFactoryModel.getCalendar(data).then((res) => {
          this.breakDate = res;
        });
      },
      getFlightInformation(data) {
        crudFactoryModel.getCondition(data).then((res) => {
          this.flightInformation = res;
        })
      },
      //类型
      // getType(data){
      //   // TODO  可以优化点
      //   let name = "";
      //   let s = [];
      //   switch (data) {
      //     case "1":
      //       name = "开会";
      //       break
      //     case "2":
      //       name = "吃饭";
      //       break
      //     case "3":
      //       name = "休息";
      //       break
      //     case "4":
      //       name = "其他";
      //       break
      //   }
      //   return name;
      // }

    },
    mounted: function () {
      const that = this;
      window.onresize = function temp() {
        that.height = document.documentElement.clientHeight - 180 + "px;";
      };
    },
  };
</script>


<style>
  .is-selected {
    color: #1989FA;
  }

  .details-title {
    font-size: 18px;
    color: #333;
    font-weight: 700;
  }

  .row-con {
    display: flex;
    flex-flow: row wrap;
  }

  .row-con .card {
    height: 100%;
  }
</style>
